"""
客户管理路由 (正确架构: Routes -> Service(含Mapper) -> Models)
"""
from flask import Blueprint, request
from flask_jwt_extended import jwt_required
from utils import ApiResponse
from services.guest_service import GuestService

api_bp = Blueprint('guest', __name__, url_prefix='/admin')
guest_service = GuestService()


@api_bp.route('/guests', methods=['GET'])
@jwt_required()
def get_guests():
    """获取客户列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        name = request.args.get('name', '').strip()
        phone = request.args.get('phone', '').strip()
        vip_level = request.args.get('vip_level', type=int)
        
        data = guest_service.get_guests_paginated_dto(
            page=page,
            per_page=per_page,
            name=name,
            phone=phone,
            vip_level=vip_level
        )
        
        return ApiResponse.success(data=data)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)


@api_bp.route('/guests/<int:guest_id>', methods=['GET'])
@jwt_required()
def get_guest(guest_id):
    """获取客户详情"""
    try:
        data = guest_service.get_guest_dto(guest_id)
        if not data:
            return ApiResponse.error(msg='客户不存在', code=404)
        
        return ApiResponse.success(data=data)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)


@api_bp.route('/guests', methods=['POST'])
@jwt_required()
def create_guest():
    """创建客户"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['name', 'phone', 'idNumber']
        for field in required_fields:
            if field not in data or not data[field]:
                return ApiResponse.error(msg=f'缺少必填字段: {field}', code=400)
        
        result = guest_service.create_guest_dto(
            name=data['name'],
            phone=data['phone'],
            id_number=data['idNumber'],
            email=data.get('email'),
            address=data.get('address'),
            vip_level=data.get('vipLevel', 0),
            total_spent=data.get('totalSpent', 0)
        )
        
        return ApiResponse.success(data=result, msg='客户创建成功', code=201)
    except ValueError as e:
        return ApiResponse.error(msg=str(e), code=400)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)


@api_bp.route('/guests/<int:guest_id>', methods=['PUT'])
@jwt_required()
def update_guest(guest_id):
    """更新客户"""
    try:
        data = request.get_json() or {}
        
        # 构建更新数据
        update_data = {}
        field_mapping = {
            'name': 'name',
            'phone': 'phone',
            'idNumber': 'id_number',
            'email': 'email',
            'address': 'address',
            'vipLevel': 'vip_level',
            'totalSpent': 'total_spent'
        }
        
        for api_field, model_field in field_mapping.items():
            if api_field in data and data[api_field] is not None:
                update_data[model_field] = data[api_field]
        
        result = guest_service.update_guest_dto(guest_id, **update_data)
        if not result:
            return ApiResponse.error(msg='客户不存在', code=404)
        
        return ApiResponse.success(data=result, msg='客户更新成功')
    except ValueError as e:
        return ApiResponse.error(msg=str(e), code=400)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)


@api_bp.route('/guests/<int:guest_id>', methods=['DELETE'])
@jwt_required()
def delete_guest(guest_id):
    """删除客户"""
    try:
        result = guest_service.delete_guest(guest_id)
        if not result:
            return ApiResponse.error(msg='客户不存在', code=404)
        
        return ApiResponse.success(msg='客户删除成功')
    except ValueError as e:
        return ApiResponse.error(msg=str(e), code=400)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)

